//
//  ZDBUserInfoAboutViewController.m
//  ZDB
//
//  Created by 微笑吧阳光 on 2020/3/28.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBUserInfoAboutViewController.h"
#import "ZDBSettingTableViewCell.h"
#import "BDImagePicker.h"
#import "TZImagePickerController.h"
#import "ZDBUpdateNameViewController.h"
#import "ZDBUpdatePhoneViewController.h"
#import "ZDBForgetViewController.h"
@interface ZDBUserInfoAboutViewController ()
<UITableViewDelegate,UITableViewDataSource,TZImagePickerControllerDelegate>
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSDictionary * userInfoDicc;
@property(strong,nonatomic)UIImage * selectImage;
@property(strong,nonatomic)NSString * kUploadIconImageToken;
@property(strong,nonatomic)NSString * imageKey;
@end

@implementation ZDBUserInfoAboutViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.userInfoDicc = [[DJLoginHelper sharedInstance]cj_UserDicc];
    [self creat_UI];
    [self step_Data];
   //  [self getAvatarQiniuToken];
    
}




-(void)creat_UI{
    
    [self.view addSubview:self.tableView];
    UIView * topView = [BBControl createViewWithFrame:CGRectMake(0, 0, kScreenWidth, 5)];
    topView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = topView;

    
}

-(void)step_Data{
    
    self.dataSource = @[
        @{
            @"type":@(3),
            @"title":@"修改头像"
        },
        @{
                   @"type":@(2),
                   @"title":@"修改昵称"
               },
        @{
                   @"type":@(2),
                   @"title":@"更改手机号"
               },
        @{
                   @"type":@(1),
                   @"title":@"修改密码"
               }

    ].mutableCopy;
    
    [self.tableView reloadData];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZDBSettingTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"ZDBSettingTableViewCell" forIndexPath:indexPath];
   cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.row ==0) {
    [cell.headerImage sd_setImageWithURL:[NSURL URLWithString:[self.userInfoDicc jsonString:@"headImage"]] placeholderImage:PlaceHolderImage];
        
    }else if (indexPath.row ==1){
        cell.subLab.text = [self.userInfoDicc jsonString:@"nikeName"];
        
    }else if (indexPath.row ==2){
        NSString *numberString = [[self.userInfoDicc jsonString:@"userName"] stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        cell.subLab.text = numberString;
    }
    cell.dataDicc = self.dataSource[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (indexPath.row) {
        case 0:
        {
            [self getAvatarQiniuToken];
        }
            break;
        case 1:
           {
               ZDBUpdateNameViewController * updateVC = [ZDBUpdateNameViewController new];
               updateVC.title = @"修改昵称";
               updateVC.nicknameStr = [self.userInfoDicc jsonString:@"nikeName"];
               WEAKSELF
               updateVC.updetaInfoClickBlock = ^(BOOL isUpdate,NSString * infoname) {
                   STRONGSELFFor(weakSelf);
                   if (strongSelf.updetaInfoClickBlock) {
                       strongSelf.updetaInfoClickBlock(YES);
                   }
                   NSMutableDictionary * dataDicc = [NSMutableDictionary dictionaryWithDictionary:strongSelf.userInfoDicc];
                   [dataDicc setValue:infoname forKey:@"nikeName"];
                   strongSelf.userInfoDicc =  dataDicc;
                   [strongSelf.tableView reloadData];
               };
               [self.navigationController pushViewController:updateVC animated:YES];
           }
               break;
        case 2:
           {
               ZDBUpdatePhoneViewController * phoneVC = [ZDBUpdatePhoneViewController new];
               phoneVC.title = @"修改手机号";
               WEAKSELF
                         phoneVC.updetaInfoClickBlock = ^(BOOL isUpdate,NSString * nePhone) {
                             STRONGSELFFor(weakSelf);
                             if (strongSelf.updetaInfoClickBlock) {
                                 strongSelf.updetaInfoClickBlock(YES);
                             }
                             NSMutableDictionary * dataDicc = [NSMutableDictionary dictionaryWithDictionary:strongSelf.userInfoDicc];
                             [dataDicc setValue:nePhone forKey:@"nikeName"];
                             strongSelf.userInfoDicc =  dataDicc;
                             [strongSelf.tableView reloadData];
                         };
               [self.navigationController pushViewController:phoneVC animated:YES];
           }
               break;
        case 3:
           {
               
               ZDBForgetViewController * eVC = [ZDBForgetViewController new];
                eVC.title = @"修改密码";
              [self.navigationController pushViewController:eVC animated:YES];
           }
               break;
            
        default:
            break;
    }

}
//获取七牛头像token
-(void)getAvatarQiniuToken{
    [self showLoadingAnimation];
    WEAKSELF
    [[SmileHttpTool sharedInstance] getTokenFromQiNiu:@"" resultBlock:^(BOOL isSuccess, NSString *token) {
        [self stopLoadingAnimation];
        STRONGSELFFor(weakSelf)
        if (isSuccess) {
            strongSelf.kUploadIconImageToken = token;
            [strongSelf editHeaderBtnClick];
        }
    }];
}
-(void)editHeaderBtnClick{
    
    WEAKSELF
//    [BDImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
//        STRONGSELFFor(weakSelf)
//
//        if (image) {
//            strongSelf.selectImage = image;
//            [strongSelf upLoadImageToQINiu:image andBlock:^(NSString *imageKey) {
//                NSLog(@"imageKey----%@",imageKey);
//                strongSelf.imageKey = imageKey;
//
//
//            }];
//        }
//    }];
//
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.needCircleCrop = YES;
    imagePickerVc.allowCrop = YES;
    imagePickerVc.barItemTextColor = [UIColor colorWithHexString:@"#333333"];
    imagePickerVc.naviTitleColor = [UIColor colorWithHexString:@"#333333"];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        STRONGSELFFor(weakSelf);
        if (photos.count >0) {
            self.selectImage =photos.firstObject;
                        [strongSelf upLoadImageToQINiu:self.selectImage andBlock:^(NSString *imageKey) {
                            NSLog(@"imageKey----%@",imageKey);
                            strongSelf.imageKey = imageKey;
                            [strongSelf updateNickNameAndHeadImage];
            
                        }];
        }
     
    }];
    imagePickerVc.modalPresentationStyle = 0;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
    
}
-(void)updateNickNameAndHeadImage{

    
    [self showLoadingAnimation];

    ZDBSettingTableViewCell * fristCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    NSString  * loginurl = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"user_updateNickNameAndHeadImage"];
       NSMutableDictionary * diccc = [NSMutableDictionary dictionary];
       [diccc setValue:self.imageKey forKey:@"headImage"];
       //[diccc setValue:@"iOS" forKey:@"macAddress"];
       WEAKSELF
       [[SmileHttpTool sharedInstance] POST :loginurl parameters:diccc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
         STRONGSELFFor(weakSelf)

           if (statusCode==0) {
              [JMNotifyView showNotify:@"保存成功" isSuccessful:YES];
               
               if (strongSelf.updetaInfoClickBlock) {
                   strongSelf.updetaInfoClickBlock(YES);
               }
               fristCell.headerImage.image = self.selectImage;
           }else{
                [JMNotifyView showNotify:message isSuccessful:NO];
           }

            [strongSelf stopLoadingAnimation];
       } failure:^(id responseObject, NSError *error) {
           NSLog(@"error----%@",error);
           [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
           [self stopLoadingAnimation];
       }];
    
    //[self reBtnClik];
    
    
}

#pragma mark -- 上传封面到七牛
-(void)upLoadImageToQINiu:(UIImage *)coverImg andBlock:(void (^)(NSString  *))imageBackBlock{
      
    if (self.kUploadIconImageToken) {
        
        NSData *data =UIImageJPEGRepresentation(coverImg, 0.8);
        
        QNUploadManager *upManager = [[QNUploadManager alloc] init];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *key = [NSString stringWithFormat:@"iOS%@.jpg", [formatter stringFromDate:[NSDate date]]];
        [upManager putData:data key:key token:self.kUploadIconImageToken
                  complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                      if (!kDictIsEmpty(resp)) {
                          !imageBackBlock ? : imageBackBlock([resp jsonString:@"key"]);
                      }
                  } option:nil];
    }else{
        [self getAvatarQiniuToken];
    }
}

- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker{
    
    
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight  - kStatusBarAndNavigationBarHeight)style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = CELLCOLOR;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.sectionHeaderHeight = 0.01;
        _tableView.sectionFooterHeight = 0.01;
        _tableView.backgroundColor =  VIEWBGCOLOR;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerNib:[UINib nibWithNibName:@"ZDBSettingTableViewCell" bundle:nil]  forCellReuseIdentifier:@"ZDBSettingTableViewCell"];
    
    }
    return _tableView;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
